package com.library.management.controller.auth;

import com.library.management.common.Result;
import com.library.management.domain.user.dto.LoginDTO;
import com.library.management.domain.user.vo.LoginVO;
import com.library.management.domain.user.dto.RegisterDTO;
import com.library.management.domain.user.User;
import com.library.management.service.token.TokenService;
import com.library.management.service.user.UserService;
import com.library.management.util.JwtUtil;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.expiration}")
    private Long expiration;

    @PostMapping("/login")
    public Result<LoginVO> login(@Valid @RequestBody LoginDTO loginDTO) {
        // 查询用户
        User user = userService.getByUsername(loginDTO.getUsername());
        if (user == null) {
            return Result.error("用户名或密码错误");
        }

        // 校验密码
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            return Result.error("用户名或密码错误");
        }

        // 校验状态
        if (user.getStatus() == 0) {
            return Result.error("账号已被禁用");
        }

        // 生成token
        String token = jwtUtil.generateToken(user.getUsername());

        // 将token存储到Redis
        tokenService.storeToken(user.getUsername(), token, expiration / 1000);

        // 构建返回数据
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);

        // 创建并设置用户信息
        LoginVO.UserInfo userInfo = new LoginVO.UserInfo();
        BeanUtils.copyProperties(user, userInfo);
        loginVO.setUserInfo(userInfo);

        return Result.success(loginVO);
    }

    @PostMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization") String authorization) {
        System.out.println("收到退出登录请求，Authorization: " + authorization);
        
        if (authorization != null && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);
            System.out.println("提取的token: " + token);
            
            try {
                String username = jwtUtil.extractUsername(token);
                System.out.println("提取的用户名: " + username);
                
                if (username != null) {
                    // 从Redis中删除token
                    tokenService.deleteToken(username);
                    System.out.println("已从Redis删除用户 " + username + " 的token");
                }
            } catch (Exception e) {
                System.err.println("退出登录时发生错误: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.out.println("Authorization头格式不正确或为空");
        }
        
        return Result.success();
    }

    @PostMapping("/register")
    public Result<Void> register(@Valid @RequestBody RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (userService.getByUsername(registerDTO.getUsername()) != null) {
            return Result.error("用户名已存在");
        }

        // 创建用户对象
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        
        // 设置默认状态为启用
        user.setStatus(1);

        // 保存用户
        userService.save(user);

        return Result.success();
    }
} 